package com.example.weight.wormHandle.cultivate;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.example.weight.wormHandle.garbageDisposal.researchDevelopment.BatchGroupNumber;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BigBugBreedInNav extends AppCompatActivity {

    private String name,factory;

    private MiddleWormBox selectBox, toAddBox;

    
    private String fenhe_Text;
    private String firstAdd_Text;
    private String secondAdd_Text;

    private String fenhe_belongTo_id = "";
    private String firstAdd_belongTo_id = "";
    private int secondAdd_belongTo_id = -1;

    private Spinner fenhe_batchGroupNumber;
    private Spinner sp_add;
    private Spinner secondAdd_batchGroupNumber;

    //备选批次等列表
    private List<MiddleWormBox> middleWormBoxList;
    private List<MiddleWormBox> addList;
    private List<BatchGroupNumber> secondAdd_batchGroupNumberList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_big_bug_breed_in_nav);

        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");
//        System.out.println(factory);

        toAddBox = (MiddleWormBox) previousIntent.getSerializableExtra("selectBox");

//        selectBox = new MiddleWormBox("100", "P2021", "Z110", "W520", "S250", "1.00");

        TitleBar titleBar=findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {

            @Override
            public void onLeftClick(View v) {
                BigBugBreedInNav.this.finish();
            }
            @Override
            public void onTitleClick(View v) { }
            @Override
            public void onRightClick(View v) { }
        });

        fenhe_batchGroupNumber = findViewById(R.id.select_fenhe_batch);
        sp_add = findViewById(R.id.select_firstAdd_batch);
//        secondAdd_batchGroupNumber = findViewById(R.id.select_secondAdd_batch);

        middleWormBoxList = new ArrayList<>();
        addList = new ArrayList<MiddleWormBox>();



        // 分盒数据
        RequestQueue queue = Volley.newRequestQueue(this);
        String url1 = Config.url + "/hsmpy/middleWormBreedingFeed/getlist_fh" + "?factory=" + factory;
        StringRequest stringRequest1 = new StringRequest(Request.Method.GET, url1,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (!jsonObject.isNull("data")) {
                                JSONArray data = jsonObject.getJSONArray("data");
                                if( data.length()>0){
                                    for (int i=0; i < data.length(); i++){
                                        JSONObject record = data.getJSONObject(i);
                                        MiddleWormBox temp;
                                        if(!record.getString("id").equals("")
                                                && !record.getString("batch").equals("")
                                                && !record.getString("wormGroup").equals("")
                                                && !record.getString("hatchBoxNumber").equals("")
                                                && record.has("smallBugBreedBoxNumber")
                                                && record.has("small_bug_breed_box_weight")
                                        ){
                                            Log.d("fenhe record", String.valueOf(record));

                                            temp = new MiddleWormBox(record.getString("id")
                                                    , record.getString("batch"), record.getString("wormGroup")
                                                    , record.getString("hatchBoxNumber"), record.getString("smallBugBreedBoxNumber"), record.getString("small_bug_breed_box_weight"));
                                            middleWormBoxList.add(temp);
                                            Log.d("fenhe",temp.toString());
                                        }
                                    }
                                    if(middleWormBoxList.size() == 0){
                                        Toast.makeText(BigBugBreedInNav.this,
                                                "没有符合要求的数据，请检查小虫盒号与盒重是否存在", Toast.LENGTH_SHORT).show();
                                    }else {
                                        ArrayAdapter<MiddleWormBox> adapter = new ArrayAdapter<>(BigBugBreedInNav.this, android.R.layout.simple_spinner_item,middleWormBoxList);
                                        fenhe_batchGroupNumber.setAdapter(adapter);
                                        fenhe_batchGroupNumber.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                            @Override
                                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                                fenhe_belongTo_id = middleWormBoxList.get(position).getId();
                                                selectBox = middleWormBoxList.get(position);
                                            }

                                            @Override
                                            public void onNothingSelected(AdapterView<?> parent) {
                                                fenhe_belongTo_id = "";
                                            }
                                        });
                                        fenhe_batchGroupNumber.setSelection(0,true);
                                    }
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(BigBugBreedInNav.this,
                        "获取待分盒信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest1.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest1);

        // 加料数据
        RequestQueue queue1 = Volley.newRequestQueue(this);
        String url2 = Config.url + "/hsmpy/middleWormBreedingFeed/getlist" + "?factory=" + factory;
        StringRequest stringRequest2 = new StringRequest(Request.Method.GET, url2,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (!jsonObject.isNull("data")) {
                                JSONArray data = jsonObject.getJSONArray("data");
                                if( data.length()>0){
                                    for (int i=0; i < data.length(); i++){
                                        JSONObject record = data.getJSONObject(i);
                                        MiddleWormBox temp;
                                        if(!record.getString("id").equals("")
                                                && !record.getString("batch").equals("")
                                                && !record.getString("wormGroup").equals("")
//                                                && !record.getString("hatchBoxNumber").equals("")
                                                && record.has("smallBugBreedBoxNumber")
//                                                && record.has("smallBugBoxMaterialWeight")
                                                && record.has("tinyBugBreedBoxNumber")
                                                && record.has("smallBugMaterialWeight")
                                                && record.has("smallBugBoxMaterialWeight")
                                                && record.has("number")
                                                && record.has("perBugMaterialWeight")
//                                                && record.has("bigBugPerBoxBreedMaterialWeight")
                                                && record.has("serial")
                                                && record.has("bigBugBreedStartTime")
                                        ){
                                            temp = new MiddleWormBox(record.getString("id")
                                                    , record.getString("batch")
                                                    , record.getString("wormGroup")
                                                    , record.getString("tinyBugBreedBoxNumber")
                                                    , record.getString("smallBugBreedBoxNumber")
//                                                    , record.getString("smallBugBoxMaterialWeight")
                                                    , record.getString("smallBugMaterialWeight")
                                                    , record.getString("smallBugBoxMaterialWeight")
                                                    , record.getString("number")
                                                    , record.getString("perBugMaterialWeight")
//                                                    , record.getString("bigBugPerBoxBreedMaterialWeight")
                                                    , record.getString("serial")
//                                                    ,"0"
                                                    , record.getString("bigBugBreedStartTime"));
                                            System.out.println("记录："+record);
                                            System.out.println("记录："+temp);
                                            addList.add(temp);
                                        }
                                    }
                                    if(addList.size() == 0){
                                        Toast.makeText(BigBugBreedInNav.this,
                                                "没有能够进行加料的数据", Toast.LENGTH_SHORT).show();
                                    }else {
                                        ArrayAdapter<MiddleWormBox> adapter1 = new ArrayAdapter<>(BigBugBreedInNav.this, android.R.layout.simple_spinner_item,addList);
                                        sp_add.setAdapter(adapter1);
                                        sp_add.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                            @Override
                                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                                firstAdd_belongTo_id = addList.get(position).getId();
                                                toAddBox = addList.get(position);
                                            }

                                            @Override
                                            public void onNothingSelected(AdapterView<?> parent) {
                                                fenhe_belongTo_id = "";
                                            }
                                        });
                                        fenhe_batchGroupNumber.setSelection(0,true);
                                    }
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(BigBugBreedInNav.this,
                        "获取待分盒信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest2.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue1.add(stringRequest2);
    }

    public void turnFenHe(View view) {
        if (fenhe_belongTo_id.equals("")) {
            Toast.makeText(this, "请选择可分盒的批次、组别、小虫盒号", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent =new Intent(BigBugBreedInNav.this, fenhe.class);
        intent.putExtra("name", name);
//        intent.putExtra("fenhe_belongTo_id", fenhe_belongTo_id+"");
//        intent.putExtra("fenhe_Text", fenhe_Text);
        intent.putExtra("selectBox", selectBox);
        intent.putExtra("factory", factory);
        startActivityForResult(intent, 1);
    }

    public void turnFirstJiaoLiao(View view) {
        if (toAddBox == null) {
            Toast.makeText(this, "请先进行分盒", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent =new Intent(BigBugBreedInNav.this, BigBugFirstFeed.class);
        intent.putExtra("name", name);
        intent.putExtra("toAddBox", toAddBox);
        intent.putExtra("factory", factory);
        startActivityForResult(intent, 1);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        Log.d("refresh","1");
        if (data != null) {
            boolean needRefresh = data.getBooleanExtra("needRefresh", true);
            if (needRefresh)
                refresh();
        }
    }

    // 刷新activity
    public void refresh() {
//        Log.d("refresh", "2");
        finish();
        Intent intent = new Intent(BigBugBreedInNav.this,
                BigBugBreedInNav.class);
        intent.putExtra("name", name);
        intent.putExtra("factory", factory);
        startActivity(intent);
    }
}